package com.arlen.conf;

import com.alibaba.druid.pool.DruidDataSource;
import com.arlen.service.LoginService;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.sql.DataSource;
import javax.annotation.PostConstruct;

@Configuration
@SuppressWarnings("all")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Autowired
    LoginService loginImpl;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")
                .successForwardUrl("/success") //登陆成功转发
                //.successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))
                .failureUrl("/error.html")
                //.failureForwardUrl()
                //.failureHandler(new MyAuthenticationFailureHandler("http://https://mail.163.com/"))
                .loginProcessingUrl("/login").permitAll();

        http.authorizeRequests()
                .antMatchers("/login.html").access("permitAll()");
                //.antMatchers("/image/**").access("hasAuthority('admin')")
//                .antMatchers(HttpMethod.POST,"/error.html").permitAll()
//                .anyRequest().authenticated()
//                .antMatchers("/xxx/image/**").permitAll()
//                .mvcMatchers("image/**").servletPath("/xxx").permitAll();
                //.antMatchers("/approve.html").authenticated();
                //.antMatchers("/approve.html").hasAuthority("admin")
//                .antMatchers("/xxx").hasAnyAuthority("admin","add")
              //  .anyRequest().access("myAccessImpl.myAccess(httpServletRequest,authentication)")
                //.antMatchers("/Role.html").hasAnyRole("arlen");
        //        .antMatchers().hasIpAddress("");


      // http.authorizeRequests().anyRequest().access("@myAccess.myAccess(request,authentication)");

        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler("403.html"));

        http.rememberMe().userDetailsService(loginImpl)
                        .tokenRepository(repository);

        http.csrf().disable();
    }


    @Autowired
    private PersistentTokenRepository repository;

   // @Autowired
   // @Qualifier("dataSource")
   // private DataSource dataSource; //因为在配置文件中已经配置了 dataSource所以直接注入就好

    //PersistentTokenRepository 有两个实现类 InMemoryTokenRepositoryImpl 基于内存存储
                                // JdbcTokenRepositoryImpl 基于jdbc存储
    @Bean
    public PersistentTokenRepository  getPersistentTokenRepository(){
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        repository.setDataSource(dataSource);
        repository.setCreateTableOnStartup(true);  //启动时是否创建表的配置
        return repository;
    }
    @Value("${spring.datasource}")
    private static String dviver;


    private static DruidDataSource dataSource =null;
    static {
        dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dviver);
        dataSource.setUrl("jdbc:mysql://rm-bp103z5076g14z0dbao.mysql.rds.aliyuncs.com/arlen?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT");
        dataSource.setUsername("root");
        dataSource.setPassword("Ymz2580@");
    }
}
